// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import {
    Form,
    Row,
    Col,
    Input,
    Cascader,
    Tag,
    Icon,
    DatePicker,
    Select,
    Button,
    Upload,
    Modal,
    Divider,
    Tooltip,
    message,
    Radio, Checkbox
} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
import {isEmpty, isArray, cloneDeep, chunk, set, get} from 'lodash'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import { reg } from 'utils/util'
// 当前组件样式
import styles from './integralManagementDetail_cloudStyle.less'
import Uploader from "widget/Upload";
import classnames from 'classnames/bind'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import PopUpSelect from 'widget/PopUpSelectnoModal/PopUpSelect'
let cx = classnames.bind(styles);
const { Option } = Select;
const FormItem = Form.Item
const { TextArea } = Input
const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
}
const imageLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 22 },
}

const formItemLayout4 = {
	labelCol: { span: 4 },
	wrapperCol: { span: 20 },
}

const routeView = function ({ dispatch, model, form }) {
    // 表单的子函数
    const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
    // 取出model对象，命名空间
    const { modelObj, namespace } = model
    let { merchandiseList, merchantList,pageType, isClone, formData,regionList,areaList,medias,selectAddressList,query,clique,areaList1,city,discityList} = modelObj
    // modelObj.xxx获取model中状态机的值

    // updateProduct createProduct
    function save() {
        let methodName={ edit: 'update', add: 'create', detail: '' }[pageType]
        if(isClone){//clone方式新建
            methodName='create'
        }
        validateFields((err) => {
            if (err) {
                return false
            } else {
                dispatch({
                    type: `${namespace}/${methodName}`,
                    payload: {resetFields}
                })
            }
        })
    }

    function updateImageModel(value) {
        medias.push(value);
        // 分发到model
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { medias }
        })
    };

    function removeImgUrl(index) {
        medias.splice(index, 1)
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { medias }
        })
    }

    function inputChange(value, type) {
        if(type == "regionId"){
            let data = regionList.filter(item=>{
                return item.regionId == value
            })
            formData.regionName = data[0].regionName;
        }
        if(type == "jfMerchantId"){
            let data = merchantList.filter(item=>{
                return item.value == value
            })
            formData.jfMerchantName = data[0].label;
        }
        if(type == "jfMerchandiseId"){
            let data = merchandiseList.filter(item=>{
                return item.value == value
            })
            formData.jfMerchandiseName = data[0].label;
        }
        if(type == 'sumLimit'){
            value = Number(value)
        }
        formData[type] = value;
        form.resetFields();
        dispatch({
          type: `${namespace}/updateStore`,
          payload: { formData }
        })
    }

    function isUnionChange(value, type){
        if(value != '1'){
            formData.jfMerchantName = ''
            formData.jfMerchantId = ''
        }
        formData[type] = Number(value);
        form.resetFields();
        dispatch({
          type: `${namespace}/updateStore`,
          payload: { formData }
        })
    }

    /*
    ===================================兑换项目代码开始
    */
   const sellerTableColumn = [
        { title: '项目名称', width: 100, dataIndex: 'productName', key: 'productId',render:(e,item)=>{
            return item.productName ||item.name
        } },
        // { title: '所属城市',width:170, dataIndex: 'city', key: 'city' ,render:(a, item, index, d, e, f)=>{
        //     //console.log(item)
        //     let arr = ['北京市','重庆','上海','天津']
        //     if(arr.indexOf(item.provinceName)>-1){
        //         return `${item.cityName}`
        //     }else{
        //         return `${item.provinceName||''}${item.provinceName&&item.cityName&&' - '||''}${item.cityName||''}`
        //     }
        // }
        // },
        {
            title:'项目地址',width:200,dataIndex:'mapAddress',key:'mapAddress'
        }
    ];

    let sellerQueryList = [
        // {name: '区域公司', type: 'select', key: 'regionId',list:addressList,notNeedAll:true},
        { name: '省市', type: 'cascader', list: cloneDeep(areaList), key: ['province', 'city', 'county'], value: '' },
        { name: '项目名称', type: 'text', key: 'name', value: '' },
        { name: '', type: 'hidden', key: 'shelfStatus', value: '1' },
    ];

    const sellerSelectedColumn = [
        { title: '项目名称', width: 200, dataIndex: 'productName', key: 'productId' ,render:(e,item)=>{
            return  item.productName ||item.name
        }},
        // { title: '所属城市', dataIndex: 'cityName', key: 'cityName',render:(a, item, index, d, e, f)=>{
        //     //console.log(item)
        //     // console.log(item)
        //     let arr = ['北京','重庆','上海','天津']
        //     let provinceName=''
        //     let cityName=''
        //     // console.log(areaList.length)
        //     for(let i=1;i<areaList.length;i++){
        //         if(item.province==areaList[i].value){
        //             provinceName=areaList[i].label
        //             if(arr.indexOf(provinceName)>-1){
        //                 provinceName=''
        //             }
        //             for(let j=0;j<areaList[i].children.length;j++){
        //                 if(item.city==areaList[i].children[j].value){
        //                     cityName=areaList[i].children[j].label
        //                     // console.log(provinceName,cityName)
        //                     return <span>{`${provinceName}${provinceName && '-'}${cityName}`}</span>
        //                 }
        //             }
        //         }
        //     }
            
        // }},
        {
            title:'项目地址',width:280,dataIndex:'mapAddress',key:'mapAddress',render:(e,item)=>{
                return  item.mapAddress
            }
        }
        
    ];

    //活动范围选择start
        //删除form表单函数
        function remove(k) {
            query.provinceCodes = query.provinceCodes.filter((key, index) => index !== k)
            query.cityCodes = query.cityCodes.filter((key, index) => index !== k)
            let mcity = city.filter((key, index) => index !== k)
            dispatch({
                type: `${namespace}/updateStore`,
                payload: { city:mcity, query }
            });
        }

    	//动态增加form表单
        const formItems1 = query.provinceCodes && query.provinceCodes.map((k, index) => (
            <Row>
                <Col span={12}>
                    <Form.Item
                        {...formItemLayout4}
                        required={false}
                        key={index}
                        label="商品上架城市"
                    >
                        {getFieldDecorator(`provinceCodes[${index}]`, {
                            validateTrigger: ['onChange', 'onBlur'],
                            rules: [{
                                required: false,
                                whitespace: true,
                                message: "请选择或者删除此范围",
                            }],
                            initialValue: query.provinceCodes[index]
                        })(
                            <Select style={{width:'95%'}} onSelect={(value, option) => { getProvince(value, option, index) }} disabled={pageType == 'detail'} >
                            {<Select.Option value='0' key='0' disabled={!JSON.parse(clique)}>全国</Select.Option>}
                                
                                {areaList1.map((item, i) => {
                                    return (
                                        <Select.Option value={item.value} key={JSON.stringify(item.children)}>{item.label}</Select.Option>
                                    )
                                })}
                            </Select>
                        )}
                        
                    </Form.Item>
                </Col>
    
                {query.provinceCodes && query.provinceCodes.length > 1 && pageType != 'detail'? (
                    <Col span={2}>
                        <Icon
                            className="dynamic-delete-button"
                            type="minus-circle-o"
                            disabled={query.provinceCodes.length === 1 }
                            onClick={() => remove(index)}
                        />
                    </Col>
                ) : null}
                {index == 0 &&
                    <Col span={2}><Tooltip title="说明：上架城市的用户才能看到该商品。"><Icon type="question-circle" className={cx('iconTip')} /></Tooltip></Col>
                }
            </Row>
    
        ));
    

        const formItems2 = query.cityCodes && query.cityCodes.map((x, y) => (
            <div>{query.provinceCodes[y] != "0"?
            <div style={{marginLeft:'9%'}}>
                <div >
            {!query.wholeCountry && query.provinceCodes[y]>0 ?<Checkbox
                    indeterminate={query.cityCodes[y]&&city[y]&&query.cityCodes[y].length!=0 &&(query.cityCodes[y].length !=  city[y].length) }
                        onChange={(e)=>onCheckAllChange(y,e)}
                    checked={query.cityCodes[y]&&city[y]&&(query.cityCodes[y].length ==  city[y].length)}
                >
                    全选
                </Checkbox>:null}
                </div>
                <Form.Item
                    required={false}
                    key={y}
                >
                    {getFieldDecorator(`cityCodes[${y}]`, {
                       initialValue: query.cityCodes[y],
                    })(
                        <Checkbox.Group disabled={pageType == 'detail'} style={{ width: "100%" }} onChange={(value) => getCity(value, y)}>
                          {city[y]?city[y].map(item=>{return (<Checkbox disabled={discityList.includes(item.value) || pageType == 'detail'} value={item.value}>{item.label}</Checkbox>)}):''}
                        </Checkbox.Group>
                    )}
                </Form.Item>
    
            </div>
            :''}</div>
        ));

        const formItems = formItems1&&formItems1.map((x, y) => (
            <div key={y}>{formItems1[y]}{formItems2[y]}</div>))

                //增加全选
    function onCheckAllChange(y,e){
        let arr = []
        if(e.target.checked){
            city[y].forEach((item,idx)=>{
               arr.push(item.value)
            })
        }
        query.cityCodes[y] = arr
        dispatch({
            type:`${namespace}/updateStore`,
            payload:{query}
        })
        form.resetFields([`cityCodes[${y}]`])
    }

                //判断当选择的全部城市是多选框的全国默认被选上，并且不可用
    function getProvince(e, option, i) {
        
        if (e == 0) {
		   query.wholeCountry = true
		   query.cityCodes = [['0']];
        } else if (e != 0) {
            query.wholeCountry = false
            query.cityCodes[i] = []
            // dispatch({
            //   type:`${namespace}/getDiscity`,
            //   payload:{pId:e}
            // })
        }
		query.provinceCodes[Number(i)] = e;
        city[i] = JSON.parse(option.key)
        form.resetFields([`cityCodes[${i}]`])
        form.resetFields([`provinceCodes[${i}]`])
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { city,  query }
        });
        form.resetFields(['useRange'])
    }

        //获取所选城市
        function getCity(e, i) {
            query.cityCodes[i] = e
            //query.city
           dispatch({
               type: `${namespace}/updateStore`,
               payload: { query }
           });
       }
           //增加form表单函数
    function add() {
        query.provinceCodes.push("")
        query.cityCodes.push([])
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { query }
        });
    }
        //活动范围选择end

    /*
    ============================兑换项目代码结束
    */

    return (
        <div className={cx('public_listMain')}>
            <div className="functionButton">
                {
                    pageType=='detail'?null:<Button type='primary' loading={modelObj.btnLoading} onClick={() => { save() }}>保存</Button>
                }
                
            </div>
            <CollapsiblePanels title="商品信息" hideUpDownBtn={true}>
            <div>
									{/* <FormItem>
										<Row>
											<div style={{ "fontWeight": "600" }}>活动发布范围 </div>
											<div style={{fontSize:'12px',lineHeight:'12px'}}>{warn}</div>
										</Row>
										
									</FormItem> */}
									{formItems}
									{pageType == 'detail' ? null :
										<FormItem required='false'>
											{getFieldDecorator('useRange', {
												rules:[{
												validator: function(rule, str, callback){
													// if(!gameBaseDetail.promoteStatus){
														if(query.wholeCountry||query.provinceCodes.length>0){
															callback();
														}else{
															callback('请选择城市范围');
														}
													// }else{
													// 	callback();
													// }
													}//todo
												} 
												],
											})(
											<Button style={{marginLeft:'9%'}} type='primary' onClick={(e) => { add() }}>新增上架城市</Button>)
											}
										</FormItem>
									}
								</div>
                <div>
                    <Row className="col" >
                        {/* <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="选择区域">
                                {getFieldDecorator(`regionId`, {
                                    initialValue:  formData.regionId || '',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择区域' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'regionId')}>
                                  {regionList.map((item,idx)=>{
                                      return <Select.Option key={item.key}  value={item.value}>{item.label}</Select.Option>
                                    })}
                                  
                                </Select>))}
                            </FormItem>
                        </Col> */}
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="是否上架">
                                {getFieldDecorator(`issj`, {
                                    initialValue:  formData.issj || '',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择是否上架' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'issj')}>
                                    <Select.Option value="Y">是</Select.Option>
                                    <Select.Option value="N">否</Select.Option>
                                </Select>))}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='商品名称'>
                                {getFieldDecorator('giftName', {
                                    initialValue: formData.giftName,
                                    rules: [
                                        { required: pageType != 'detail',  message: '请输入商品名称'},
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入商品名称'}
                                    onChange={(e) => { inputChange(e.target.value, 'giftName') }}
                                />)}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="商品简介">
                                {getFieldDecorator(`giftJj`, {
                                    initialValue:  formData.giftJj || '',
                                    rules: [
                                        { required: false, whitespace: true, message: '请选择是否上架' },
                                    ],
                                })((<TextArea
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e.target.value, 'giftJj')}>
                                </TextArea>))}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        {/* <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="商品类别">
                                {getFieldDecorator(`jfMerchandiseId`, {
                                    initialValue:  formData.jfMerchandiseId || '',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择商品类别' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'jfMerchandiseId')}>
                                  {merchandiseList.map((item,idx)=>{
                                      return <Select.Option key={item.key}  value={item.value}>{item.label}</Select.Option>
                                    })}
                                  
                                </Select>))}
                            </FormItem>
                        </Col> */}
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="是否支持邮寄">
                                {getFieldDecorator(`isPost`, {
                                    initialValue:  formData.isPost || '',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择是否上架' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'isPost')}>
                                    <Select.Option value="Y">邮寄</Select.Option>
                                    <Select.Option value="N">自取</Select.Option>
                                </Select>))}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='兑换积分'>
                                {getFieldDecorator('integral', {
                                    initialValue: formData.integral,
                                    rules: [
                                        { required: pageType != 'detail',  message: '请输入兑换积分'},
                                        { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入整数' }
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入兑换积分'}
                                    onChange={(e) => { inputChange(e.target.value, 'integral') }}
                                />)}
                            </FormItem>
                        </Col>
                        {/* <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='单次兑换数量限制'>
                                {getFieldDecorator('singleLimit', {
                                    initialValue: formData.singleLimit,
                                    rules: [
                                        { required: pageType != 'detail',  message: '请输入单次兑换数量限制'},
                                        { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入整数' }
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入单次兑换数量限制'}
                                    onChange={(e) => { inputChange(e.target.value, 'singleLimit') }}
                                />)}
                            </FormItem>
                        </Col> */}
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='累计兑换数量限制'>
                                {getFieldDecorator('sumLimit', {
                                    initialValue: formData.sumLimit,
                                    rules: [
                                        { required: pageType != 'detail',  message: '请输入累计兑换数量限制'},
                                        { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入整数' }
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入累计兑换数量限制'}
                                    onChange={(e) => { inputChange(e.target.value, 'sumLimit') }}
                                />)}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        {/* <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label="是否商家联盟">
                                {getFieldDecorator(`isUnion`, {
                                    initialValue:  formData.isUnion?formData.isUnion +'':'',
                                    rules: [
                                        { required: pageType!='detail', whitespace: true, message: '请选择是否商家联盟' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => isUnionChange(e, 'isUnion')}>
                                    <Select.Option value='1'>是</Select.Option>
                                    <Select.Option value='0'>否</Select.Option>
                                </Select>))}
                            </FormItem>
                        </Col> */}
                        <Col span={12} style={{display: formData.isUnion == 1?'block': 'none'}}>
                            <FormItem {...formItemLayout}
                                      label="商家名称">
                                {getFieldDecorator(`jfMerchantId`, {
                                    initialValue:  formData.jfMerchantId || '',
                                    rules: [
                                        { required: formData.isUnion == '1'&&pageType!='detail'? true: false, whitespace: true, message: '请选择商家名称' },
                                    ],
                                })((<Select
                                    disabled={pageType == 'detail'} 
                                  onChange={(e) => inputChange(e, 'jfMerchantId')}>
                                  {merchantList.map((item,idx)=>{
                                      return <Select.Option key={item.key}  value={item.value}>{item.label}</Select.Option>
                                    })}
                                  
                                </Select>))}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='备注'>
                                {getFieldDecorator('remark', {
                                    initialValue: formData.remark,
                                    rules: [
                                        { required: false, whitespace: true,  message: '请输入备注'},
                                    ],
                                })(<Input
                                    disabled={pageType == 'detail'}
                                    placeholder={'备注'}
                                    onChange={(e) => { inputChange(e.target.value, 'remark') }}
                                />)}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout}
                                      label='库存数量'>
                                {getFieldDecorator('stock', {
                                    initialValue: formData.stock,
                                    rules: [
                                        { required: false,  message: '请输入库存数量'},
                                        { pattern: /^(0|[1-9][0-9]*)$/, message: '请输入整数' }
                                    ],
                                })(<Input 
                                    disabled={pageType == 'detail'}
                                    placeholder={'请输入库存数量'}
                                    onChange={(e) => { inputChange(e.target.value, 'stock') }}
                                />)}
                            </FormItem>
                        </Col>
                    </Row>
                </div>
            </CollapsiblePanels>
            <CollapsiblePanels title="商品图" hideUpDownBtn={true}>
                <Row>
                    <FormItem {...imageLayout} label="商品图">
                        <Uploader uploadedUrls={medias}
                                  removeFileCbf={(index) => { removeImgUrl(index) }}
                                  uploadSuccessCbf={(imgUrl) => { updateImageModel(imgUrl) }}
                                  ossFolderName="admin/integral/pic"
                                  showType='6'
                                  fileType='image'
                                //   fileMaxSize='0.2'
                                  unsetWidth={true}
                                  minCropBoxWidth={320}
                                  minCropBoxHeight={320}
                                  maxFiles='1' />

                    </FormItem>

                    <Col span={12}>
            <span style={{ color: '#999', marginLeft: '4%' }}>
            图片分辨率需为320px*320px，支持jpg，png格式。备注图  要求把商品抠出来白底展现
              </span>
                    </Col>
                </Row>
            </CollapsiblePanels>
            <CollapsiblePanels title="兑换项目地址" hideUpDownBtn={true}>
                <PopUpSelect
                    tableColumn={sellerTableColumn}
                    selectedColumn={sellerSelectedColumn}
                    selectedTableScroll={{ x: 320 }}
                    queryList={cloneDeep(sellerQueryList)}
                    isSave={true}
                    refreshByEnter={true}
                    requestUrl='admin/estate/adminList'
                    title='选择工程名称'
                    respListKey='rows'
                    idKey='productId'
                    onItem={selectAddressList}
                    onChange={(e) => {
                        
                        // let productIds=[]
                        selectAddressList = [];
                        e.map((item)=>{
                            // productIds.push(item.productId);
                            // let p = {
                            //     projectAddr:item.mapAddress,
                            //     // province:item.province,
                            //     // provinceName:item.provinceName,
                            //     projectname:item.name && item.name!=""?item.name:item.productName,
                            //     // latitude:item.latitude,
                            //     // longitude:item.longitude,
                            //     // cityName:item.cityName,
                            //     // city:item.city,
                            //     projectid:item.productId,
                            //     // projectId:item.outerId||item.projectId,
                            //     // estatePhone:item.estatePhone
                            // };
                            
                            let p = {
                                city:item.city,
                                cityCode:item.city,
                                estatePhone:item.estatePhone,
                                latitude:item.latitude,
                                longitude:item.longitude,
                                mapAddress:item.mapAddress,
                                productName:item.name && item.name!=""?item.name:item.productName,
                                productId:item.productId,
                            };
                            debugger
                            selectAddressList.push(p);
                        })
                        dispatch({
                            type: `${namespace}/updateStore`,
                            payload: {selectAddressList}
                        })
                    }}
                ></PopUpSelect>
            </CollapsiblePanels>
        </div>
    )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))